import Router from '@koa/router'
import { verifyToken } from '../utils/token'

const mustAuth = ['/crud', '/upload']

export const auth: Router.Middleware = async (ctx, next) => {
    const token = ctx.headers.authorization
    let verifyed = false
    if (token) {
        try {
            const tk = token.replace('Bearer ', '')
            const user = await verifyToken(tk)
            ctx.state.user = user
            verifyed = true
        } catch (error) {
            verifyed = false
        }
    }

    const url = ctx.url
    // 如果没有要验证的路径，则直接执行下一个中间件
    if (!mustAuth.some((path) => url.startsWith(path))) {
        await next()
        return
    } else if (!verifyed) {
        ctx.status = 401
        ctx.body = { success: false, msg: 'token已过期' }
        return
    }
    await next()
}
